package ts.group.webapp.market.common.core.spring.view;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.view.AbstractView;

import ts.group.webapp.market.common.imp.support.XLSTransformerExt;


/**
 * 
 * @author  jiang.zhaoxin@starit.com.cn
 * @date    2012-11-18 上午11:03:34
 * @version 
 */
public class JXLSExcelView extends AbstractView {
	private final Logger logger = LoggerFactory.getLogger(JXLSExcelView.class);
	
	public static final String EXCEL_EXPORT_FILE_NAME = "exportFileName";
	public static final String EXCEL_TEMPLATE_FILE_NAME_PREFIX = "QPTemp-";
	
	/** The content type for an Excel response */
	private static final String CONTENT_TYPE = "application/vnd.ms-excel";
	
	private XLSTransformerExt transformer;
	/**
	 * Default Constructor.
	 * Sets the content type of the view to "application/vnd.ms-excel".
	 */
	public JXLSExcelView() {
		transformer = new XLSTransformerExt();
		setContentType(CONTENT_TYPE);
	}
	
	@Override
	protected boolean generatesDownloadContent() {
		return true;
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String fileName = request.getParameter(EXCEL_EXPORT_FILE_NAME);
		fileName = fileName.replaceAll(" ", "");
		
		response.setHeader("content-disposition","attachment; filename="+new String(fileName.getBytes("gb2312"),"ISO8859-1")+".xls");
		String path = getClass().getClassLoader().getResource(".").getPath() + "excel/templates/" + 
				EXCEL_TEMPLATE_FILE_NAME_PREFIX+"_"+fileName+".xls";
		File file = new File(path);
		if(!file.exists()) {
			createExportTemplate(model, file);
			logger.info("创建Excel导出模板：" + path);
		}
		
		ServletOutputStream out = response.getOutputStream();
		transformer.transformXLS(path, model, out);
	  	out.flush();
	}
	
	@SuppressWarnings("unchecked")
	private void createExportTemplate(Map<String, Object> model, File file) {
		List<Map<String, Object>> list = (List<Map<String, Object>>)model.get("columns");
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		
		HSSFFont headfont = workbook.createFont();
	    headfont.setFontName("宋体");
	    headfont.setFontHeightInPoints((short)10);// 字体大小
	    headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
		HSSFCellStyle style0 = workbook.createCellStyle();
        style0.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style0.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style0.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style0.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style0.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style0.setFont(headfont);
        
        HSSFCellStyle style1 = workbook.createCellStyle();
        style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
		HSSFRow row0 = sheet.createRow(0);
		HSSFRow row1 = sheet.createRow(1);
		
		int i=0;
		for(Map<String, Object> map : list) {
			HSSFCell cel0 = row0.createCell(i, HSSFCell.CELL_TYPE_STRING);
			cel0.setCellValue((String)map.get("NAME"));
			cel0.setCellStyle(style0);
			HSSFCell cel1 = row1.createCell(i, HSSFCell.CELL_TYPE_STRING);
			cel1.setCellValue("${datas." + map.get("COLUMN_NAME") + "}" );
			cel1.setCellStyle(style1);
			
			i++;
		}
		
		try {
			FileOutputStream fileOut = new FileOutputStream(file);
			workbook.write(fileOut);
	        fileOut.close();  
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
